package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;
import com.gsk.europepharma.salesReport.utils.UtilsSalesReport;

/**
 * Gestion des donnees pour l'affichage du tableau contenant le top UGA ou la liste des medecins.
 */
public class DataGridUGA extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Variables de session
		HttpSession sessionObject = request.getSession();
		Integer cs_adm_pdt = (Integer) sessionObject.getAttribute("cs_adm_pdt");
		Integer cs_adm_rgpt = (Integer) sessionObject.getAttribute("cs_adm_rgpt");
		Integer cs_adm_prstn = (Integer) sessionObject.getAttribute("cs_adm_prstn");
		Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
		// Integer cs_month = (Integer) sessionObject.getAttribute("cs_month");
		// Fin de session
		
		String idGeog = request.getParameter("idGeog");
		Integer idGeogInteger = Integer.parseInt(idGeog);
		String nivGeog = request.getParameter("nivGeog");
		
		String source = request.getParameter("source");
		Integer CS_SRC = Integer.parseInt(source);
		String unite = request.getParameter("unite");
		// String periode = request.getParameter("periode");
		
		String codeUga = request.getParameter("codeUga");
		
		JSONArray jsonArrayLines = new JSONArray();
		
		if (codeUga != null && !codeUga.equals("")) { // ACTION : affichage des medecins 
			
			String cs_division_string = request.getParameter("cs_division");
			Integer cs_division = Integer.parseInt(cs_division_string);
			String periodeActivite = request.getParameter("periodeActivite");
			String specialite = request.getParameter("specialite");
			String segments = request.getParameter("segments");
			
			tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
			Session session = salesDAO.getSession();
						
			Query req = null;
			
			String strReq = salesDAO.QUERY_QUERY_LISTE_CONTACT_UGA; 
			
			req = session.getNamedQuery(strReq); 
			req.setString("uga", codeUga);
			
			ArrayList result = new ArrayList(req.list());
			Iterator iter = result.iterator();
			
			int i = 0;
			
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
				
				JSONObject jsonObjectLine = new JSONObject();
				jsonObjectLine.put("id", i);
				i++;
				jsonObjectLine.put("name", val[4].toString());
				jsonObjectLine.put("firstname", val[5].toString());
				jsonObjectLine.put("zipCode", val[7].toString());
				jsonObjectLine.put("city", val[8].toString());
				jsonObjectLine.put("spe", val[9].toString());
				
				if (i % 2 == 0) {
					jsonObjectLine.put("cible", "B"); // TODO:
				} else {
					jsonObjectLine.put("cible", "A"); // TODO:
				}
				jsonObjectLine.put("nbCalls", i + " / " + i); // TODO:
				jsonObjectLine.put("dernVis", "02/10/" + i); // TODO:
				jsonObjectLine.put("proVis", "01/01/" + i); // TODO:
				
				jsonArrayLines.add(jsonObjectLine);
			}
			
		} else { // ACTION : affichage du top ten UGA 
			
			// Nombre UGA par page 
			int nombreUGAParPage = Integer.parseInt(request.getParameter("itemsParPage"));
			// Indice de debut 
			String start = request.getParameter("start");
			
			int nombreTotalUGA = 0;
			// Requete pour determiner le nombre total UGA 
			tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
			Session session = salesDAO.getSession();
			Query req = null;
			String strReq = salesDAO.QUERY_TOP_UGA_COUNT; 
			req = session.getNamedQuery(strReq);
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_network", cs_network);
			req.setString("nivGeog", nivGeog);
			req.setInteger("idGeog", idGeogInteger); 
			if (request.getParameter("filter") != null) {
				String tab[] = request.getParameter("filter").split("\"");
				String value = tab[7];
				String property = tab[11];
				req.setString("fieldFilterUga", property);
				req.setString("valueFilterUga", value);
			} else {
				req.setString("fieldFilterUga", "nofilter");
				req.setString("valueFilterUga", "");
			}
			ArrayList result = new ArrayList(req.list());
			nombreTotalUGA = Integer.parseInt(result.get(0).toString());
			// Mise en session du nombre UGA
			sessionObject.setAttribute("nombreUGA", result.get(0).toString());
			
			// Calcul des indices min et max 
			int beginIndex = Integer.parseInt(start);
			int endIndex = Integer.parseInt(start) + nombreUGAParPage;
			if (endIndex > nombreTotalUGA) {
				endIndex = nombreTotalUGA;
			}
			
			// Requete
			salesDAO = new tbSpBoSRSectoDAO();
			session = salesDAO.getSession();
			req = null;
			strReq = "";
			strReq = salesDAO.QUERY_TOP_UGA; 
			req = session.getNamedQuery(strReq);
			req.setParameter("data1",		unite + "CC");
			req.setParameter("data2",		unite + "MM");
			req.setInteger("cs_adm_pdt",		cs_adm_pdt);
			req.setInteger("cs_adm_rgpt",	cs_adm_rgpt);
			req.setInteger("cs_adm_prstn",	cs_adm_prstn);
			req.setInteger("CS_SRC",		CS_SRC);
			req.setInteger("cs_network",	cs_network);
			req.setString("nivGeog",		nivGeog);
			req.setInteger("idGeog",		idGeogInteger); 
			req.setInteger("min",			beginIndex);
			req.setInteger("max",			endIndex);
			if (request.getParameter("sort") != null) {
				String tab[] = request.getParameter("sort").split("\"");
				String property = tab[3];
				String order = tab[7];
				req.setString("fieldOrder", property);
				req.setString("ascDescOrder", order);
			} else {
				req.setString("fieldOrder", "noorder");
				req.setString("ascDescOrder", "ASC");
			}
			
			if (request.getParameter("filter") != null) {
				String tab[] = request.getParameter("filter").split("\"");
				String value = tab[7];
				String property = tab[11];
				req.setString("fieldFilterUga", property);
				req.setString("valueFilterUga", value);
			} else {
				req.setString("fieldFilterUga", "nofilter");
				req.setString("valueFilterUga", "");
			}
			
			result = new ArrayList(req.list());
			Iterator iter = result.iterator();
			
			int i = 1;
			
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
		           
				JSONObject jsonObjectLine = new JSONObject();
				jsonObjectLine.put("id", i);
				i++;
				jsonObjectLine.put("codeUga", val[0].toString());
				jsonObjectLine.put("uga", val[1].toString());
				
				Double vol = 0.0;
				if (val[2] != null) {
					vol = Double.parseDouble(val[2].toString());
				}
				Double vol_1 = 0.0;
				if (val[3] != null) {
					vol_1 = Double.parseDouble(val[3].toString());
				}
				Double vol_tt = 0.0;
				if (val[4] != null) {
					vol_tt = Double.parseDouble(val[4].toString());
				}
				Double vol_tt_1 = 0.0;
				if (val[5] != null) {
					vol_tt_1 = Double.parseDouble(val[5].toString());
				}
				
				Double vol2 = 0.0;
				if (val[6] != null) {
					vol2 = Double.parseDouble(val[6].toString());
				}
				Double vol2_1 = 0.0;
				if (val[7] != null) {
					vol2_1 = Double.parseDouble(val[7].toString());
				}
				Double vol2_tt = 0.0;
				if (val[8] != null) {
					vol2_tt = Double.parseDouble(val[8].toString());
				}
				Double vol2_tt_1 = 0.0;
				if (val[9] != null) {
					vol2_tt_1 = Double.parseDouble(val[9].toString());
				}
				
				if (val[2] != null && val[4] != null && vol_tt != 0.0) {
					Double pmCm3 = UtilsSalesReport.getPm(vol, vol_tt, 1);
					jsonObjectLine.put("pmCm3", pmCm3);
				} else {
					jsonObjectLine.put("pmCm3", "");
				}
				if (val[2] != null && val[3] != null && val[4] != null && val[5] != null && vol_tt != 0.0 && vol_tt_1 != 0.0) {
					Double pmCm3Delta = UtilsSalesReport.getDeltaPm(vol, vol_1, vol_tt, vol_tt_1, 1);
					jsonObjectLine.put("pmCm3Delta", pmCm3Delta);
				} else {
					jsonObjectLine.put("pmCm3Delta", "");
				}
				
				if (val[6] != null && val[8] != null && vol2_tt != 0.0) {
					Double pm = UtilsSalesReport.getPm(vol2, vol2_tt, 1);
					jsonObjectLine.put("pm", pm);
				} else {
					jsonObjectLine.put("pm", "");
				}
				if (val[6] != null && val[7] != null && val[8] != null && val[9] != null && vol2_tt != 0.0 && vol2_tt_1 != 0.0) {
					Double pmDelta = UtilsSalesReport.getDeltaPm(vol2, vol2_1, vol2_tt, vol2_tt_1, 1);
					jsonObjectLine.put("pmDelta", pmDelta);
				} else {
					jsonObjectLine.put("pmDelta", "");
				}
		
				jsonArrayLines.add(jsonObjectLine);
			}
			
			HashMap hm = new HashMap();
			JSONObject res = new JSONObject();
			res.put("total",	nombreTotalUGA);
			res.put("data",		jsonArrayLines);
			res.put("id",		"gridUGAStore");
			hm.put("result",	res);
			
			JSONObject json = JSONObject.fromObject(hm);
			response.addHeader("Content-Type", "application/json");
	        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
	        response.getOutputStream().flush();
			
			return null;
		}
		
		HashMap hm = new HashMap();
		hm.put("lines", jsonArrayLines);
		
		JSONObject json = JSONObject.fromObject(hm);
		response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();
		
		return null;
	}
	
}
